$(function(){
	var setting = {
			view: {
				addHoverDom: addHoverDom,
				removeHoverDom: removeHoverDom,
				selectedMulti: false
			},
			edit: {
				enable: true,
				editNameSelectAll: true
//				showRemoveBtn: showRemoveBtn,
//				showRenameBtn: showRenameBtn
			},
			data: {
				simpleData: {
					enable: true
				}
			},
			callback: {
				beforeDrag: beforeDrag,
				beforeEditName: beforeEditName,
				beforeRemove: beforeRemove,
				beforeRename: beforeRename,
				onRemove: onRemove,
				onRename: onRename
			}
		};		
		var log, className = "dark";
		function beforeDrag(treeId, treeNodes) {
			return false;
		}
		function beforeEditName(treeId, treeNode) {
			className = (className === "dark" ? "":"dark");
//			showLog("[ "+getTime()+" beforeEditName ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			zTree.selectNode(treeNode);
			setTimeout(function() {
//				if (confirm("进入节点 -- " + treeNode.name + " 的编辑状态吗？")) {
				if (confirm("确定编辑么?")) {
					setTimeout(function() {zTree.editName(treeNode);}, 0);
				}
			}, 0);
			return false;
		}
		function beforeRemove(treeId, treeNode) {
			className = (className === "dark" ? "":"dark");
//			showLog("[ "+getTime()+" beforeRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			zTree.selectNode(treeNode);
//			if( confirm("确认删除 节点 -- " + treeNode.name + " 吗？")){
			if( confirm("确认删除  " + treeNode.name + " 吗？")){
				delChapter(treeNode.id);
			}
		}
		function onRemove(e, treeId, treeNode) {
			showLog("[ "+getTime()+" onRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
		}
		function beforeRename(treeId, treeNode, newName, isCancel) {
			className = (className === "dark" ? "":"dark");
//			showLog((isCancel ? "<span style='color:red'>":"") + "[ "+getTime()+" beforeRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name + (isCancel ? "</span>":""));
			if(treeNode.name==newName)return;
			if (newName.length == 0) {
				setTimeout(function() {
					var zTree = $.fn.zTree.getZTreeObj("treeDemo");
					zTree.cancelEditName();
					alert("章节名称不能为空."+treeNode.id); //修改
				}, 0);
				return false;
			}
			updateChapter(treeNode.id,treeNode.pId,newName);
			return true;
		}
		function onRename(e, treeId, treeNode, isCancel) {
			showLog((isCancel ? "<span style='color:red'>":"") + "[ "+getTime()+" onRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name + (isCancel ? "</span>":""));
		}
		function showRemoveBtn(treeId, treeNode) {
			return !treeNode.isFirstNode;
		}
		function showRenameBtn(treeId, treeNode) {
			return !treeNode.isLastNode;
		}
		function showLog(str) {
			if (!log) log = $("#log");
			log.append("<li class='"+className+"'>"+str+"</li>");
			if(log.children("li").length > 8) {
				log.get(0).removeChild(log.children("li")[0]);
			}
		}
		function getTime() {
			var now= new Date(),
			h=now.getHours(),
			m=now.getMinutes(),
			s=now.getSeconds(),
			ms=now.getMilliseconds();
			return (h+":"+m+":"+s+ " " +ms);
		}

		var newCount = 1;
		function addHoverDom(treeId, treeNode) {
			var sObj = $("#" + treeNode.tId + "_span");
			if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0 ) return;
			var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
				+ "' title='add node' onfocus='this.blur();'></span>";
			sObj.after(addStr);
			var btn = $("#addBtn_"+treeNode.tId);
			if (btn) btn.bind("click", function(){//添加
				var zTree = $.fn.zTree.getZTreeObj("treeDemo");
				name = "new node" + (newCount++);
				zTree.addNodes(treeNode, {id:(100 + newCount), pId:treeNode.id, name:name});
				addChapter(treeNode.id,name);
				return false;
			});
		};
		function removeHoverDom(treeId, treeNode) {			
			$("#addBtn_"+treeNode.tId).unbind().remove();
		};
//		function selectAll() {
//			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
//			zTree.setting.edit.editNameSelectAll =  $("#selectAll").attr("checked");
//		}
	
		
	$.fn.zTree.init($("#treeDemo"), setting, getChapter());
//	$("#selectAll").bind("click", selectAll);

	
	
    /*************添加标签*************/
//	function addTag() {
//		$.get(serverURL + "tag/getList", function(data) {
//			try{
//				if (data.code == 0) {
//					$(".row").empty();
//					if (data.data.length > 0) {
//						var html = "<select name='' id='jquery-tagbox-select-options' style='width:220px;' placeholder='添加标签' class=‘form-control’ data-toggle=‘tooltip’ data-placement=‘top’ title=‘请选择标签’>";
//						$.each(data.data, function(i, k) {
//							html += "<option  value=" + k.tagId + ">" + k.name+ "</option>";
//						});
//						$(".row").html(html+"</select><input type='text' id='jquery-tagbox-select' />");
//						
//						$("#jquery-tagbox-text").tagBox();
//						$("#jquery-tagbox-select").tagBox({
//							enableDropdown : true,
//							dropdownSource : function() {
//								return $("#jquery-tagbox-select-options");
//							}
//						});
//					} else {
//						$("#jquery-tagbox-select-options").html("<option>无数据</option>");
//					}
//				} else if (data.code != -1) {
//					alert("数据加载出错，请稍后重试");
//				}
//			}catch(e){
//				
//			}
//		});
//	}
	
	function getChapter(){
		var zodes = "#id:0, pId:0, name:\"根目录\", open:true@,";
		$.ajax({ // 此处用同步处理，避免出现val()比reload早的问题
			url : serverURL + "view/course/getChapter?courseId="+courseId,
			type : "get",
			async : false,
			contentType: "application/json", 
	        dataType: "json", 
			success : function(data) {
				if(data.code == 0 ){
					$.each(data.data, function(i, k) {
						if(k.parentId == 0){
							zodes += "#id:"+k.chapterId+", pId:"+k.parentId+", name:\""+k.chapterName+"\", open:true@,";
						}else{
							zodes += "#id:"+k.chapterId+", pId:"+k.parentId+", name:\""+k.chapterName+"\"@,";
						}
					});
					zodes=	zodes.replace(/\#/g, "{");
					zodes = zodes.replace(/\@,/g, "},");
				} else if (data.code != -1) {
					alert("数据加载出错，请稍后重试");
				}
			}
		});
		return eval('([' + zodes.substring(0,zodes.length-1) + '])');
	}
	
	function addChapter(parentId,name){
		$.post(serverURL + "view/course/addChapter", {"parentId" : parentId,"chapterName":name,"courseId":courseId}, function(data) {
			if (data.code == 0) {
				alert("添加成功");
				window.location.href="course/addCourse.htm?courseId="+courseId;
			} else if (data.code != -1) {
				alert("添加失败,请稍后重试");
			}
		});
	}
	
	function updateChapter(id,parentId,name){
		$.post(serverURL + "view/course/updateChapter", {"chapterId":id,"parentId" : parentId,"chapterName":name}, function(data) {
			if (data.code == 0) {
				alert("修改成功");
			} else if (data.code != -1) {
				alert("修改失败,请稍后重试");
			}
		});
	}
	function delChapter(id){
		$.get(serverURL + "view/course/delChapter", {"chapterId":id}, function(data) {
			if (data.code == 0) {
				alert("删除成功");
			} else if (data.code != -1) {
				alert("删除失败,请稍后重试");
			}
		});
	}
});